package dbPhase.hypeerweb;

/**
 * TerminalNodeState is a state that represents a node that is a terminal node.
 *
 * @see NodeState
 *
 * @pre singleton - TerminalNodeState
 *
 *
 */
public class TerminalNodeState extends NodeState {

	static TerminalNodeState singleton;

	private TerminalNodeState() {

	}

	static TerminalNodeState getSingleton() {
		if (singleton == null) {
			singleton = new TerminalNodeState();
		}
		return singleton;
	}

	public static final int STATE_ID = 4;

	@Override
	public Node find(Node thisNode ) {

		Node smallestDP = thisNode.getSmallestDownPointer();
		Node parent = thisNode.getSmallestNeighbor();

		return smallestDP.nodeState.search(parent.getWebId().getValue(),
									smallestDP.getWebId().getValue(),
									smallestDP);

	}

	@Override
	public Node search(int lb, int ub, Node thisNode ) {

		if (thisNode.getWebId().getValue() == (lb + 1) && ub == (lb + 1)) {
			return thisNode; //thisNode.addChild(newNode);
		}

		Node smallestDP = thisNode.getSmallestDownPointer();

		//parent is the smallest Neighbor
		Node parent = thisNode.getSmallestNeighbor();

		if (ub > smallestDP.getWebId().getValue()) {
			ub = smallestDP.getWebId().getValue();
		}
		if (lb < parent.getWebId().getValue()) {
			lb = parent.getWebId().getValue();
		}
		return smallestDP.nodeState.search(lb, ub, smallestDP);
	}
	@Override
	public int getStateId() {

		return STATE_ID;
	}

	@Override
	public String toString() {
		return "Terminal Node State";
	}

	@Override
	public Node findDP(Node thisNode) {
		Node smallestDP = thisNode.getSmallestDownPointer();

		//parent is the smallest Neighbor
		Node parent = thisNode.getSmallestNeighbor();

		return smallestDP.nodeState.searchDP(parent.getWebId().getValue(),
									smallestDP.getWebId().getValue(),
									smallestDP);
	}

	@Override
	public Node searchDP(int lb, int ub,Node thisNode) {
		if (thisNode.getSmallestNeighbor().getWebIdValue() == lb && ub == (lb + 1)) {
			return thisNode;
		}

		Node smallestDP = thisNode.getSmallestDownPointer();

		//parent is the smallest Neighbor
		Node parent = thisNode.getSmallestNeighbor();

		if (ub > smallestDP.getWebId().getValue()) {
			ub = smallestDP.getWebId().getValue();
		}
		if (lb < parent.getWebId().getValue()) {
			lb = parent.getWebId().getValue();
		}
		return smallestDP.nodeState.searchDP(lb, ub,smallestDP);
	}

}
